package com.cloudrui.service.wechat.neteasy;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.cloudrui.service.wechat.WeChatMsgHandler;
import com.cloudrui.service.wechat.neteasy.bean.Msg;
import com.cloudrui.service.wechat.neteasy.bean.NetEasyMessageBean;
import com.cloudrui.service.wechat.neteasy.bean.OneMsg;
import com.cloudrui.service.wechat.neteasy.bean.Sports;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;


/**
 * 数字代表mcode
 * 球员数据统计http://nba.sports.163.com/api/match/webboxscore/1127021008.json
 * @author macky
 *
 */
public class NetLiveService implements Runnable{
	
	private String url;
	
	private String id;
	
	private String mcode;
	
	public NetLiveService(String url,String id,String mcode) {
		this.url = url;
		this.id = id;
		this.mcode = mcode;
	}
	//URL http://data.live.126.net/live/162586.json
	private String getLiveText(String url) {
		MyHttpClient myHttpClient = Core.getInstance().getMyHttpClient();
		Map<String,String> header = new HashMap<String,String>();
		header.put("Accept-Encoding","gzip, deflate");
		StringBuffer sb = new StringBuffer("http://nba.sports.163.com/");
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-8:00"));
		int year = c.get(Calendar.YEAR);
		sb.append(year);
		sb.append("/match/stat/");
		sb.append(mcode);
		sb.append(".html");
		header.put("Referer", sb.toString());
		header.put("Connection", "keep-alive");
		HttpEntity entity = myHttpClient.doGet(url, null, false, header);
		String result;
		try {
			result = EntityUtils.toString(entity, "UTF-8");
			System.out.println("============="+result);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}
	
	public NetEasyMessageBean getMsg(String url) {
		String msg = getLiveText(url);
		NetEasyMessageBean bean = JSON.parseObject(msg, NetEasyMessageBean.class);
		
		return bean;
		
	}

	@Override
	public void run() {
		MsgService msgService = new MsgService();
		StringBuffer sb = new StringBuffer("");
		while(WeChatMsgHandler.needLive()) {
			NetEasyMessageBean bean = getMsg(url);
			Sports sp = bean.getSports();
			List<OneMsg>msgs = bean.getMessages();
			List<OneMsg> latestMsg = msgService.getLatestMsgs(msgs);
			if(latestMsg.isEmpty()) {
				sendTextRandomly(true);
				sleep(2);
				continue;
			}
			for(int i=latestMsg.size()-1;i>=0;i--) {
				OneMsg msg = latestMsg.get(i);
				sb.append("【直播员小饭】:");
				Msg actualMsg = msg.getMsg();
				String content = actualMsg.getContent();
				sb.append("[");
				sb.append(msg.getSection());
				sb.append("]");
				sb.append(content);
				
				sb.append(msg.getHomeTeam());
				sb.append(msg.getHomeScore());
				sb.append(":");
				sb.append(msg.getAwayScore());
				sb.append(msg.getAwayTeam());
				sb.append("   "+sp.getTime());
				MessageTools.sendMsgById(sb.toString(), id);
				sb.setLength(0);
				sleep(1);
			}
			//sendTextRandomly(true);
			
			sleep(2);
			
		}
	}
	
	private void sleep(int m) {
		try {
			Thread.sleep(m*1000);
		}catch(Exception e) {
			System.out.println("饭哥，我出错了，快来救我:(");
		}
	}
	
	private void sendTextRandomly(boolean random) {
		try {
			String text = GiftService.getText();
			if(random) {
				Random r = new Random();
				int size = GiftService.textMap.size();
				if(size==0)GiftService.init();
				int flag = r.nextInt(GiftService.textMap.size());
				
				if(flag<=1) {
					MessageTools.sendMsgById(text, id);
				}
			}else {
				MessageTools.sendMsgById(text, id);
			}
			
			sleep(2);
		}catch(Exception e) {
			System.out.println("饭哥，我出错了，快来救我:(");
		}
	}
}
